import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/AuthToken'
import { MessagePlugin } from 'tdesign-vue-next'

import exteriorRouter from './routers/exterior'
import basicRouter from './routers/basic'
import authorityRouter from './routers/authority'

// 外部路由
const exteriorRouterMap = [...exteriorRouter]
// 基础路由
const basicRouterMap = [...basicRouter]
// 权限路由
const authorityRouterMap = [...authorityRouter]

const routerMap = [
  {
    path: '/',
    name: 'home',
    redirect: '/home'
  },
  ...exteriorRouterMap,
  ...basicRouterMap,
  ...authorityRouterMap
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...routerMap]
})

// 获取所有路径
const getAllPath = (routerMap = []) => {
  const path = []
  routerMap.forEach((router) => {
    path.push(router.path)
    if (router.children) {
      path.push(...getAllPath(router.children))
    }
  })
  return path
}

// 鉴权
const getVerifyRouter = (authority, routerMap = []) => {
  const getAllRolesRouter = (routerMap) => {
    const path = []
    routerMap.forEach((router) => {
      path.push(router)
      if (router.children) {
        path.push(...getAllRolesRouter(router.children))
      }
    })
    return path
  }
  return getAllRolesRouter(routerMap).map((item) => {
    if (item.meta.roles.includes(authority)) return item.path
  })
}

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()

  // 权限拦截

  // 外部界面 --> 放行
  if (getAllPath(exteriorRouterMap).includes(to.path)) {
    if (!authStore.verifyAuth()) {
      next()
    } else {
      MessagePlugin.info({
        content: '您已登录，即将跳转至主页...',
        onDurationEnd: () => next({ path: '/' })
      })
    }
    return
  }

  if (!authStore.verifyAuth()) {
    // 未登录
    MessagePlugin.error({
      content: '检测到您未登录，即将为您跳转至登陆界面...',
      onDurationEnd: () => next({ path: getAllPath(exteriorRouterMap)[0] })
    })
    return
  }

  // 基础界面
  if (getAllPath(basicRouterMap).includes(to.path)) {
    next()
    return
  }

  // 权限验证
  if (getAllPath(authorityRouterMap).includes(to.path)) {
    if (getVerifyRouter(authStore.auth.authority, authorityRouterMap).includes(to.path)) {
      next()
    } else {
      MessagePlugin.error({
        content: '您的权限不足！！',
        onDurationEnd: () => next({ path: from.path })
      })
    }
    return
  }

  next()
})

export default router
